/*
 * IPerson.cpp
 *
 *  Created on: 09.05.2010
 *      Author: king
 */

#include "PersonWidget.h"

namespace etu {
namespace ui {

using namespace etu::genealogy_tree;

static const QString DATE_FORMAT = "dd/MM/yyyy";

CPersonWidget::CPersonWidget(QWidget *parent)
    : QWidget(parent)
{
	setupUi(this);
	setMaximumWidth(minimumSizeHint().width());

	QRegExp textRegExp("\\w+\-?\\w+");
	QRegExpValidator* textValidator = new QRegExpValidator(textRegExp,this);
	m_lastNameEdit->setValidator(textValidator);
	m_nameEdit->setValidator(textValidator);

	m_deadCB->setVisible(false);
	m_sexCB->setVisible(false);
}

void CPersonWidget::setPerson(Person* person)
{
  m_person = person;
  showData();
}

void CPersonWidget::setDate(QLineEdit* edit, QDate date)
{
  if (date.isValid())
    edit->setText(date.toString(DATE_FORMAT));
  else
	edit->setText("00/00/0000");
}

void CPersonWidget::showData()
{
  m_nameEdit->setText(QString(tr(m_person->getFirstName().c_str())));
  m_lastNameEdit->setText(QString(tr(m_person->getLastName().c_str())));
  setDate(m_birthDateEdit,m_person->getBirthDate().toQDate());
  setDate(m_deadDateEdit,m_person->getDeathDate().toQDate());
  m_maleRB->setChecked(m_person->getGender() == etu::genealogy_tree::MALE_GENDER);
  m_femaleRB->setChecked(m_person->getGender() == etu::genealogy_tree::FEMALE_GENDER);
  m_commentEdit->setText(QString(tr(m_person->getDescription().c_str())));
  changeDethDateState();
}

void CPersonWidget::resetData()
{
  Gender gender = (m_femaleRB->isChecked()) ? FEMALE_GENDER : MALE_GENDER;

  m_person->setBirthDate(Date::fromQDate(QDate::fromString(m_birthDateEdit->text(),DATE_FORMAT)));
  m_person->setDeathDate(Date::fromQDate(QDate::fromString(m_deadDateEdit->text(),DATE_FORMAT)));
  m_person->setDescription(QString(m_commentEdit->toPlainText().toUtf8()).toStdString());
  m_person->setFirstName(QString(m_nameEdit->text().toUtf8()).toStdString());
  m_person->setLastName(QString(m_lastNameEdit->text().toUtf8()).toStdString());
  if ( !m_sexCB->isChecked() && m_sexCB->isVisible())
	  m_person->setGender(UNKNOWN_GENDER);
  else
	  m_person->setGender(gender);

  setDate(m_birthDateEdit,m_person->getBirthDate().toQDate());
  setDate(m_deadDateEdit,m_person->getDeathDate().toQDate());
  changeDethDateState();
}

Person* CPersonWidget::getPerson()
{
  resetData();
  return m_person;
}

void CPersonWidget::changeDethDateState()
{
   if (m_deadCB->isVisible())
   {
     m_deadCB->setChecked(m_person->isDead());
     m_deadDateEdit->setVisible(m_person->isDead());
     m_dethDateLabel->setEnabled(m_person->isDead());
   }
}

}
}
